#include "SimpleCollectorData.h"

SimpleCollectorData::SimpleCollectorData(const QString& filename)
{
    QFile file(filename);
    QXmlInputSource src(&file);

    QXmlSimpleReader reader;
    reader.setContentHandler(this);

    if (!reader.parse(src)) {
        cout << "Nao foi possivel realizar o parse do arquivo" << endl;
        throw -1;
    }

}

SimpleCollectorData::~SimpleCollectorData()
{
    for (QMap<uint,SimpleEdgeElement*>::iterator it = _map.begin(); it != _map.end(); it++) {
        SimpleEdgeElement* e = it.value();
        delete e;
    }
    _map.clear();
}

void SimpleCollectorData::setDocumentLocator(QXmlLocator* locator)
{
}

bool SimpleCollectorData::startDocument()
{
    clock_gettime(CLOCK_MONOTONIC, &_startTime);

    _numOfElements = 0;
    _ancestor.clear();
    _map.clear();

    return true;
}

bool SimpleCollectorData::endDocument()
{
    clock_gettime(CLOCK_MONOTONIC, &_endTime);

//    cout << "PASS: " << (uint) timespecToMilisecond(_endTime) - timespecToMilisecond(_startTime) << " ms  +  "; // tempo de processamento em ms
//    cout << _map.find(1).value()->num_descendant << endl;

    return true;
}

bool SimpleCollectorData::startPrefixMapping(const QString& prefix, const QString& uri)
{
    return true;
}

bool SimpleCollectorData::endPrefixMapping(const QString& prefix)
{
    return true;
}

bool SimpleCollectorData::startElement(const QString& namespaceURI, const QString& localName, const QString& qName, const QXmlAttributes& atts)
{    
    SimpleEdgeElement* e = new SimpleEdgeElement();
    e->id = ++_numOfElements;
    e->num_children = 0;
//    e->num_desc = 0;

    if (!_ancestor.isEmpty()) {
        SimpleEdgeElement* parent = _ancestor.last();
        parent->num_children++;
//        parent->num_desc++;
    }

    _ancestor.push_back(e);

    for (int i = 0; i < atts.length(); ++i) {
        SimpleEdgeElement* e = new SimpleEdgeElement();
        e->id = ++_numOfElements;
        e->num_children = 0;
//        e->num_desc = 0;
        _map.insert(e->id, e);
    }

    return true;
}

bool SimpleCollectorData::endElement(const QString& namespaceURI, const QString& localName, const QString& qName)
{
    SimpleEdgeElement* e = _ancestor.last();
    _ancestor.pop_back();

//    if (!_ancestor.isEmpty()) {
//        SimpleEdgeElement* parent = _ancestor.last();
//        parent->num_desc += e->num_desc;
//    }

    _map.insert(e->id, e);
    return true;
}

bool SimpleCollectorData::characters(const QString& ch)
{
    return true;
}

bool SimpleCollectorData::ignorableWhitespace(const QString& ch)
{
    return true;
}

bool SimpleCollectorData::processingInstruction(const QString& target, const QString& data)
{
    return true;
}

bool SimpleCollectorData::skippedEntity(const QString& name)
{
    return true;
}

QString SimpleCollectorData::errorString() const
{
    return QString("Error!!!");
}

